<?php

namespace App\Kuafu\Customer\Controller\Applet;

use App\Kuafu\Customer\Enum\CodeEnum;
use App\Kuafu\Customer\Enum\PlatformCodeEnum;
use App\Kuafu\Customer\Exceptions\CustomerException;
use App\Kuafu\Customer\Model\CustomerActionLogModel;
use App\Kuafu\Customer\Model\CustomerPlatformModel;
use App\Kuafu\Customer\Service\CustomerActionLogService;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Customer\Validate\CustomerValidate;
use App\Kuafu\Customer\Enum\CustomerCodeEnum;
use App\Kuafu\Customer\Service\CustomerService;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\Shop\Service\DouyinSelfLibrary\DouyinSelfService;
use App\Kuafu\Wechat\Service\WechatService;
use App\Support\AppletEncrypt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Kuafu\Base\Controller\BaseController;

class CustomerController extends BaseController
{

    /**
     * 新增
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCustomer(Request $request)
    {
        $encryptedData = $request->encryptedData;
        $iv            = $request->iv;
        $shopId        = $this->shopId;
        $platformId    = (int)$request->header('platformId', 1);
        DB::beginTransaction();
        try {
            //获取用户unionid
            $appletToken = $request->header('APPLET-TOKEN');
            $unionid     = AppletEncrypt::getInstance()->getUserUnionid($appletToken);
            Log::info("添加手机号入口：" . json_encode(['unionid' => $unionid]));
            //获取用户sessionKey
            $sessionKey  = Redis::get("SESSION_KEY_UNIONID:" . $unionid);
            if ($platformId == PlatformCodeEnum::PLATFORM_APPLET_DOUYIN) {// 抖音小程序
                $decryptData = DouyinSelfService::decryptData($encryptedData, $iv, $sessionKey, $shopId);
            } else {
                $decryptData = WechatService::decryptData($encryptedData, $iv, $sessionKey, $shopId);
            }
            Log::info("解密数据结果:" . $decryptData);
            $decryptData = json_decode($decryptData, true);
            //判断手机号是否已经绑定
            $userInfo = CustomerService::getUserInfo(['mobile' => $decryptData['purePhoneNumber']], ['id']);
            if (!$userInfo) {
                //用户入库customer
                $customer = CustomerService::addCustomer(['mobile' => $decryptData['purePhoneNumber']]);

                // 用户留下手机号
                (new CustomerActionLogService())->asynSaveData([
                    'userId'   => $customer->id,
                    'unionId'  => $unionid,
                    'type'     => CustomerActionLogModel::ACTION_TYPE_APPLET_LEAVE_MOBILE,
                    'userInfo' => [
                        'shopId' => $this->shopId,
                        'mobile' => $decryptData['purePhoneNumber'] ?? ''
                    ]
                ]);
//                throw new CustomerException(CustomerCodeEnum::ERR_MOBILE_IS_BAND);
                $customerId = $customer->id;
            } else {
                $customerId = $userInfo->id;
            }
            //更新用户id到customerMapping
            CustomerPlatformService::setUserIdByUnionid($unionid, $platformId, $customerId);
            //更新当前unionid下的订单的用户id
            OrderService::setOrderIdsByUnionid($unionid, $customerId, $this->shopId);
            DB::commit();
            return $this->success($decryptData);
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info("添加用户错误：" . json_encode(['msg' => $exception->getMessage()]));
            return $this->fail($exception->getCode(), $exception->getMessage());
        }
    }

    public function setCustomer(Request $request)
    {
        $userId = CustomerPlatformService::getUserId($request);
        $valid  = CustomerValidate::setCustomer($userId);
        if ($valid) {
            return $this->fail(CustomerCodeEnum::ERR_CUSTOMER_DB_SET, $valid);
        }
        $reqData = [
            'name'      => $request->name,
            'headImage' => $request->headImage,
            'updatedAt' => time()
        ];
        CustomerService::setCustomer($userId, $reqData);
        Redis::del(CodeEnum::PREFIX_PLATFORM . $request->header('platformId') . ':' . CodeEnum::PREFIX_USERID . $userId);
        return $this->success();
    }
}
